package com.efounder.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.efounder.adapter.CommentAdapter;
import com.efounder.bean.CommentBean;
import com.efounder.bean.MallCloudFile;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.utils.ThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;
import static com.efounder.utils.MallRequestUtil.GOOD_UNCOMMENT_URL;

/**
 * Created by wei on 2018/3/07/01.
 *
 * @author will
 * 上传评论页面
 */

public class ToEvaluateActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = this.getClass().getSimpleName();

    TextView tv_title;
    RecyclerView recyclerView;

    private Context mContext;
    private int currentPosition = 0;
    private CommentAdapter commentAdapter;
    private CommentBean commentBean;
    private String orderBh;
    private List<CommentBean.GoodListBean> commentGoodList = new ArrayList<>();

    public static final int REQUEST_CODE_CAMERA = 18;
    private static final int REQUEST_IMAGE = 2;


    private ArrayList<String> mSelectPath = new ArrayList<>();
    public static String chatpath = ImageUtil.chatpath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_evaluate);
        orderBh = getIntent().getStringExtra("orderBh");
        mContext = this;
        initView();
        initData(orderBh);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tv_title.setText(R.string.mail_assess_sheet);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        commentAdapter = new CommentAdapter(this, commentGoodList);
        commentAdapter.setOnPositionChangedListener(new CommentAdapter.OnPositionChangedListener() {
            @Override
            public void onPositionChanged(int position) {
                currentPosition = position;
            }
        });
        commentAdapter.setOnSendCommentListener(new CommentAdapter.OnSendCommentListener() {
            @Override
            public void onSendComment(int position) {
                CommentBean.GoodListBean goodListBean = commentGoodList.get(position);
                uploadPics(position, goodListBean);
            }
        });
        recyclerView.setAdapter(commentAdapter);
    }

    private void initData(String orderBh) {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        HashMap<String, String> map = new HashMap();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orderBh", orderBh);
        MallRequestUtil.getRequest(TAG, GOOD_UNCOMMENT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                Gson gson = new GsonBuilder().serializeNulls().create();
                commentBean = gson.fromJson(response, CommentBean.class);
                if ("success".equals(commentBean.getResult())) {
                    commentGoodList.clear();
                    commentGoodList.addAll(commentBean.getGoodList());
                    commentAdapter.notifyDataSetChanged();
                } else {
                    LogUtils.e(response);
                    ToastUtils.showShort(R.string.common_text_network_error);
                }
            }

            @Override
            public void onFail(String error) {
                LogUtils.e(error);
                LoadingDataUtilBlack.dismiss();
                ToastUtils.showShort(R.string.common_text_network_error);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("--", TAG + "-----------requestCode:" + requestCode
                + ",resultCode" + resultCode);
        if (requestCode == REQUEST_PIC_SELECTE_CODE
                && resultCode == RESULT_OK) {
            //图库选择照片
            commentGoodList.get(currentPosition).getmPictureList().clear();
            ArrayList<MallCloudFile> tempCloudFiles = new ArrayList<>();
            ArrayList<String> tempList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
            for (int i = 0; i < tempList.size(); i++) {
                MallCloudFile cloudFile = new MallCloudFile();
                cloudFile.setCloudFilePath(tempList.get(i));
                tempCloudFiles.add(cloudFile);
            }
            commentGoodList.get(currentPosition).getmPictureList().addAll(tempCloudFiles);
            commentAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onClick(View v) {

    }


    private void sendComment(final int position, CommentBean.GoodListBean goodListBean, List<String> urlList) {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < urlList.size(); i++) {
            jsonObject.put("url", urlList.get(i));
            jsonArray.add(jsonObject);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userPhone", EnvironmentVariable.getUserName());
        map.put("imUserId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        map.put("goodbh", goodListBean.getGoodBh());
        map.put("content", goodListBean.getCommentContent());
        map.put("orderbh", orderBh);
        map.put("grade", String.valueOf(goodListBean.getStar()));
        // [{"url":"xxx"},{"url":"xxx"}]
        map.put("images", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.GOOD_COMMENT_ADD, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                JSONObject resultObject = JSONObject.fromObject(response);
                if (resultObject.getString("result").equals("success")) {
                    Toast.makeText(mContext, R.string.mail_submit_assess_success, Toast.LENGTH_SHORT).show();
                    commentGoodList.remove(position);
                    commentAdapter.notifyDataSetChanged();
                    //没有待评价的，则finish
                    if (commentGoodList.size() == 0) {
                        finish();
                    }
                } else {
                    Toast.makeText(mContext, R.string.mail_submit_assess_fail, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                Toast.makeText(mContext, R.string.mail_submit_assess_fail, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void uploadPics(final int position, final CommentBean.GoodListBean goodListBean) {
        if (goodListBean.getmPictureList().size() > 0) {
            LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.chat_uploading));
            //压缩图片上传
            ThreadPoolUtils.execute(new ThreadPoolUtils.Task() {
                @Override
                protected void work() {
                    ArrayList<MallCloudFile> uploadCloudFiles = new ArrayList<>();
                    for (MallCloudFile imgAddress : goodListBean.getmPictureList()) {
                        imgAddress.setCloudProgress(0);
                        //如果不是gif动图则进行裁剪压缩
                        if (!ImageUtil.isGifFile((new File(imgAddress.getCloudFilePath())))) {
                            ImageUtil.saveNewImage(imgAddress.getCloudFilePath(), 1280, 1280);
                            imgAddress.setCloudFilePath(chatpath + ImageUtil.getFileName(imgAddress.getCloudFilePath()) + ".pic");
                            uploadCloudFiles.add(imgAddress);
//                            uploadImage(chatpath + ImageUtil.getFileName(imgAddress) + ".pic");
                        } else {
//                            uploadImage(imgAddress);
                            imgAddress.setCloudFilePath(imgAddress.getCloudFilePath());
                            uploadCloudFiles.add(imgAddress);
                        }
                    }
                    PansoftCloudUtil.syncMultiFileUpload(uploadCloudFiles, new PansoftCloudUtil.MultiUpLoadListener() {
                        @Override
                        public void uploadProgress(int position, int progress, PansoftCloudUtil.CloudFile cloudFile) {
                            if (isFinishing() || isDestroyed()) {
                                return;
                            }
                            Log.d("SendPost", position + "---" + progress);
                            goodListBean.getmPictureList().get(position).setCloudProgress(progress);
                            commentAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void upLoadFinish(List<String> urlList, List<? extends PansoftCloudUtil.CloudFile> cloudFileList) {
                            if (isFinishing() || isDestroyed()) {
                                return;
                            }
                            sendComment(position, goodListBean, urlList);
                        }

                        @Override
                        public void uploadFail(Object message) {
                            LoadingDataUtilBlack.dismiss();
                            ToastUtil.showToast(ToEvaluateActivity.this, R.string.common_text_upload_fail_again);
                        }
                    });
                }
            });
        } else {
            List<String> list = new LinkedList<>();
            sendComment(position, goodListBean, list);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}